//
//  HashEncryption.m
//  game
//
//  Created by yun on 2018/3/19.
//  Copyright © 2018年 YD. All rights reserved.
//

#import "HashEncryption.h"
#import <CommonCrypto/CommonDigest.h>

#define kMD5Secret @"6d36ed7d78b64103a74037406b4125f7"

@implementation HashEncryption


#pragma mark -- md5

+ (NSString *)md5Hash:(NSString *)string{
    const char *plain = string.UTF8String;
    unsigned char *digest;
    digest = malloc(CC_MD5_DIGEST_LENGTH);
    
    CC_MD5(plain, (CC_LONG)strlen(plain), digest);
    
    NSString *encode = [self stringFromBytes:digest length:CC_MD5_DIGEST_LENGTH];
    free(digest);
    return encode;
}


#pragma mark -- 字典数据转换

+ (NSString *)dictionaryConversionString:(NSDictionary *)dic{
    
    NSArray *keys = [dic allKeys];
    NSArray *sortKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];// 为从小到大,即升序;
        return resuest;
    }];
    
    NSMutableString *str = [[NSMutableString alloc] init];
    [sortKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == sortKeys.count - 1) {
            [str appendFormat:@"%@=%@",key,[dic objectForKey:key]];
        } else {
            [str appendFormat:@"%@=%@&",key,[dic objectForKey:key]];
        }
        
    }];
    // 最后拼接secret
    [str appendFormat:@"%@",kMD5Secret];
    return str;
}

#pragma mark - Bytes转字符串
/**
 字符大小写可以通过修改“%02X”中的x修改 x：16进制小写；X:16进制大写
 */
+ (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length {
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[i]];
    }
    
    return [strM copy];
}

@end
